<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getDeliveryApplyDataApi, auditDeliveryApplyApi } from "@/api/delivery-manage"
import { type DeliveryApplyData } from "@/api/delivery-manage/types/delivery-apply"
import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, Download, RefreshRight, Picture, Loading } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"

defineOptions({
  // 命名当前组件
  name: "DeliveryApply"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// 审核通过
const handleApprove = (row: DeliveryApplyData) => {
  ElMessageBox.confirm(`确认通过配送员【${row.name}】的认证申请？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    auditDeliveryApplyApi({ id: row.id, status: 1 }).then(() => {
      ElMessage.success("审核通过成功")
      getDeliveryApplyData()
    })
  })
}

// 审核拒绝
const rejectFormRef = ref<FormInstance | null>(null)
const rejectDialogVisible = ref<boolean>(false)
const rejectForm = reactive({
  id: 0,
  rejectReason: ""
})

const handleReject = (row: DeliveryApplyData) => {
  rejectDialogVisible.value = true
  rejectForm.id = row.id
  rejectForm.rejectReason = ""
}

const submitReject = () => {
  rejectFormRef.value?.validate((valid: boolean) => {
    if (!valid) return
    
    auditDeliveryApplyApi({
      id: rejectForm.id,
      status: 2,
      rejectReason: rejectForm.rejectReason
    }).then(() => {
      ElMessage.success("审核拒绝成功")
      rejectDialogVisible.value = false
      getDeliveryApplyData()
    })
  })
}

// 查询配送员申请数据
const deliveryApplyData = ref<DeliveryApplyData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  phone: "",
  status: ""
})

const getDeliveryApplyData = () => {
  loading.value = true
  getDeliveryApplyDataApi({
    pageNo: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    name: searchData.name || undefined,
    phone: searchData.phone || undefined,
    status: searchData.status ? Number(searchData.status) : undefined
  })
    .then(({ data }) => {
      paginationData.total = data.total
      deliveryApplyData.value = data.list
    })
    .catch(() => {
      deliveryApplyData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  paginationData.currentPage === 1 ? getDeliveryApplyData() : (paginationData.currentPage = 1)
}

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getDeliveryApplyData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="姓名">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="searchData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="status" label="审核状态">
          <el-select v-model="searchData.status" placeholder="请选择" clearable style="width: 100px;">
            <el-option label="待审核" value="0" />
            <el-option label="审核通过" value="1" />
            <el-option label="审核拒绝" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <!-- 不需要新增和修改按钮 -->
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getDeliveryApplyData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="deliveryApplyData">
          <el-table-column prop="name" label="姓名" align="center" />
          <el-table-column prop="phone" label="手机号" align="center" />
          <el-table-column label="身份证" align="center">
            <template #default="scope">
              <el-image 
                v-if="scope.row.idCard" 
                :src="scope.row.idCard" 
                style="width: 50px; height: 50px" 
                fit="cover"
                :preview-src-list="[scope.row.idCard]"
                :preview-teleported="true"
              >
                <template #placeholder>
                  <el-icon><Picture /></el-icon>
                </template>
                <template #error>
                  <el-icon><Loading /></el-icon>
                </template>
              </el-image>
              <span v-else>无图片</span>
            </template>
          </el-table-column>
          <el-table-column label="学生证" align="center">
            <template #default="scope">
              <el-image 
                v-if="scope.row.studentCard" 
                :src="scope.row.studentCard" 
                style="width: 50px; height: 50px" 
                fit="cover"
                :preview-src-list="[scope.row.studentCard]"
                :preview-teleported="true"
              >
                <template #placeholder>
                  <el-icon><Picture /></el-icon>
                </template>
                <template #error>
                  <el-icon><Loading /></el-icon>
                </template>
              </el-image>
              <span v-else>无图片</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
          <el-table-column prop="status" label="审核状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 0" type="info" effect="plain" disable-transitions>待审核</el-tag>
              <el-tag v-else-if="scope.row.status === 1" type="success" effect="plain" disable-transitions>审核通过</el-tag>
              <el-tag v-else type="danger" effect="plain" disable-transitions>审核拒绝</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="申请时间" align="center" />
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template #default="scope">
              <el-button v-if="scope.row.status === 0" type="success" text bg size="small" @click="handleApprove(scope.row)">通过</el-button>
              <el-button v-if="scope.row.status === 0" type="danger" text bg size="small" @click="handleReject(scope.row)">拒绝</el-button>
              <el-button v-if="scope.row.status === 2" type="primary" text bg size="small" @click="$event => {
                ElMessageBox.alert(scope.row.rejectReason, '拒绝原因', {
                  confirmButtonText: '确定'
                })
              }">查看原因</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 拒绝原因弹窗 -->
    <el-dialog v-model="rejectDialogVisible" title="拒绝原因" width="30%">
      <el-form ref="rejectFormRef" :model="rejectForm" :rules="{
        rejectReason: [{ required: true, message: '请输入拒绝原因', trigger: 'blur' }]
      }" label-width="100px">
        <el-form-item label="拒绝原因" prop="rejectReason">
          <el-input v-model="rejectForm.rejectReason" type="textarea" :rows="4" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReject">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: center;
}
</style>